package cn.usian.controller;


import cn.usian.common.R;
import cn.usian.pojo.Category;
import cn.usian.service.CategoryService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("page")
    public R findPage(Integer page, Integer pageSize){
       return categoryService.findPage(page,pageSize);
    }

    @PostMapping()
    public R add(@RequestBody Category category){
        return categoryService.add(category);
    }
//
//    @GetMapping("{id}")
//    public R findById(@PathVariable Long id){
//        return categoryService.findById(id);
//    }


    @PutMapping
    public R updateAll(@RequestBody Category category,HttpSession session){
        Long id = (Long) session.getAttribute("category");
        category.setUpdateUser(1L);
        category.setCreateUser(1L);
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        return categoryService.updateAll(category);
    }

    @DeleteMapping
    public R deleteById(Long id){
        return categoryService.deleteById(id);
    }


    /**
     *  http://localhost:8080/category/exportExcel
     * 作用： 导出所有的类别的Excel表格
     * 注意：如果需要做文件下载有两点要求
     *      1. 返回值类型必须是void
     *      2. 方法上必须使用@ResponseBody注解，或者你已经使用@RestController
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //1. 读取模板的输入流
        InputStream inputStream = this.getClass().getResourceAsStream("/excel/cateory.xlsx");

        //2. 使用模块输入流创建工作簿
        Workbook workbook = new XSSFWorkbook(inputStream);

        //3. 得到工作单，得到第一行，并且提取样式存储到集合中
        Sheet sheet = workbook.getSheetAt(0);
        //获取行
        Row row = sheet.getRow(1);
        //定义一个集合存储单元格的样式
        List<CellStyle> cellStyleList = new ArrayList<>();
        for (int i = 1; i <=5 ; i++) {
            //得到每一个单元格的样式
            CellStyle cellStyle = row.getCell(i).getCellStyle();
            //存储到集合中
            cellStyleList.add(cellStyle);
        }
        //4. 得到所有的类别集合
        List<Category> categoryList = categoryService.findAll();

        //5. 遍历类别集合，设置样式与数据
        for (int i = 0; i < categoryList.size(); i++) {
            //得到一个类别，每一个类别就是一行数据
            Category category = categoryList.get(i);
            //创建行
            row = sheet.createRow(i+1);

            //创建单元格并且设置单元格
            //类别类型
            Cell cell = row.createCell(1);
            cell.setCellStyle(cellStyleList.get(0));
            cell.setCellValue(category.getType());

            //类别名称
            cell = row.createCell(2);
            cell.setCellStyle(cellStyleList.get(1));
            cell.setCellValue(category.getName());

            //排序
            cell = row.createCell(3);
            cell.setCellStyle(cellStyleList.get(2));
            cell.setCellValue(category.getSort());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            //创建时间
            cell = row.createCell(4);
            cell.setCellStyle(cellStyleList.get(3));
            cell.setCellValue(dateTimeFormatter.format(category.getCreateTime()));


            //修改时间
            cell = row.createCell(5);
            cell.setCellStyle(cellStyleList.get(4));
            cell.setCellValue(dateTimeFormatter.format(category.getUpdateTime()));
        }

        //6. 输出工作簿即可,通知浏览器当前是以文件下载的形式去处理内容。
        response.setHeader("content-disposition","attachment;filename=category.xlsx");
        workbook.write(response.getOutputStream());
    }



    @PostMapping("importData")
    public R importExcel(MultipartFile excelFile) throws  IOException{
        InputStream inputStream = excelFile.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheetAt = workbook.getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        for (int i = 0; i < lastRowNum; i++) {
            Row row = sheetAt.getRow(i+1);

            int type = (int) row.getCell(0).getNumericCellValue();
            String name = row.getCell(1).getStringCellValue();
            int sort = (int) row.getCell(2).getNumericCellValue();

            Date createTime = row.getCell(3).getDateCellValue();
            Instant instant = createTime.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            Date updateTime = row.getCell(4).getDateCellValue();
            Instant instant1 = updateTime.toInstant();
            ZoneId zoneId1 =  ZoneId.systemDefault();
            LocalDateTime localDateTime1 = instant1.atZone(zoneId1).toLocalDateTime();

            Category category = new Category();
            category.setType(type);
            category.setName(name);
            category.setSort(sort);
            category.setCreateTime(localDateTime);
            category.setUpdateTime(localDateTime1);
            category.setUpdateUser(1L);
            category.setCreateUser(1L);

            categoryService.add(category);
        }
        return R.success("成功");
    }

    //菜品分类查询
    @GetMapping("/list")
    public R findAllById(Integer type){
        return categoryService.findAllById(type);

    }
}
